package com.atgugu.flink.chapter08;

import com.atgugu.flink.bean.AdsClickLog;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/4/8 9:00
 * private Long userId;
 * private Long adsId;
 * private String province;
 * private String city;
 * private Long timestamp;
 */
public class Flink04_Project_High_Ads {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        env
            .readTextFile("input/AdClickLog.csv")
            .map(log -> {
                String[] data = log.split(",");
                return new AdsClickLog(
                    Long.valueOf(data[0]),
                    Long.valueOf(data[1]),
                    data[2],
                    data[3],
                    Long.parseLong(data[4]) * 1000
            
                );
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<AdsClickLog>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((log, ts) -> log.getTimestamp())
            )
            .keyBy(log -> log.getUserId() + "_" + log.getAdsId())
            .process(new KeyedProcessFunction<String, AdsClickLog, String>() {
    
                private ValueState<String> yesterdayState;
                private ValueState<Boolean> isBlackListState; // 表示当前用户对当前广播的点击是否已经加入黑名单
                private ReducingState<Long> clickCountState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    clickCountState = getRuntimeContext().getReducingState(
                        new ReducingStateDescriptor<Long>("clickCountState", Long::sum, Long.class)
                    );
    
                    //
                    isBlackListState = getRuntimeContext().getState(new ValueStateDescriptor<Boolean>("isBlackListState", Boolean.class));
    
                    yesterdayState = getRuntimeContext().getState(new ValueStateDescriptor<String>("yesterdayState", String.class));
    
                }
    
                @Override
                public void processElement(AdsClickLog value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 判断如果日志数据到了第二天, 则清空状态, 重新计算对应的黑名单
                    // 怎么判断到了第二天?
                    String today = new SimpleDateFormat("yyyy-MM-dd").format(value.getTimestamp());
                    String yesterday = yesterdayState.value();
                    if (!today.equals(yesterday)) {  // 不相等, 跨天
                        clickCountState.clear(); // 清空状态
                        isBlackListState.clear(); // 清空状态
                        
                        yesterdayState.update(today);// 今天年月存入到状态中, 到明天可以判断跨天
                        
                    }
    
    
                    //如果已经加入黑名单,则不需要再累加
                    if (isBlackListState.value() == null) {
                        clickCountState.add(1L);
                    }
    
                    Long count = clickCountState.get();  // 这个用户对这个广告的点击量
    
                    String msg = "用户: " + value.getUserId() + " 对广告: " + value.getAdsId() + " 的点击量是: " + count;
    
                    if (count > 99) {
                        // 如果一个用户被加入过, 就不应该重复加入
                        if (isBlackListState.value() == null) {
                            msg += " 超过阈值, 加入黑名单...";
                            out.collect(msg);
                            isBlackListState.update(true);
                            
                        }
                    }else{
                        out.collect(msg);
                        
                    }
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
